package com.teach.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teach.mapper.ClassMapper;
import com.teach.mapper.RoleMapper;
import com.teach.mapper.UserMapper;
import com.teach.pojo.Class;
import com.teach.pojo.RespBean;
import com.teach.pojo.Role;
import com.teach.pojo.User;
import com.teach.pojo.req.LoginReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private ClassMapper classMapper;

    @Override
    public RespBean login(LoginReq req) {
        User loginUer = userMapper.getByAccountAndRole(req.getAccount(), req.getRoleId());
        if (loginUer == null) {
            return RespBean.fail("账号不存在");
        }

        if (!loginUer.getPassword().equals(req.getPassword())) {
            return RespBean.fail("密码错误");
        }
        loginUer.setPassword("");
        Class aClass = classMapper.getClassByUserId(loginUer.getId());
        if (aClass!=null) {
            loginUer.setClassId(aClass.getId());
            loginUer.setClassName(aClass.getClassName());
        }

        loginUer.setRoleName(roleMapper.selectOne(new QueryWrapper<Role>().eq("id",req.getRoleId())).getRoleName());
        loginUer.setRoleId(req.getRoleId());
        loginUer.setPage(roleMapper.selectOne(new QueryWrapper<Role>().eq("id",req.getRoleId())).getPage());
        return RespBean.success("登录成功",loginUer);
    }

    @Override
    public List<User> getStudents(Long classId) {
        List<User> students = userMapper.getStudentsByClass(classId);
        students.forEach(item->{
            item.setClassName(classMapper.getClassByUserId(item.getId()).getClassName());
        });
        return students;
    }

    @Override
    public List<User> getStudents() {
        List<User> students = userMapper.getStudents();
        students.forEach(item->{
            item.setClassName(classMapper.getClassByUserId(item.getId()).getClassName());
        });
        return students;
    }

    @Override
    public List<User> getTeachers() {
        List<User> teachers = userMapper.getTeachers();
        teachers.forEach(item->{
            item.setClassName(classMapper.getClassByUserId(item.getId()).getClassName());
        });
        return teachers;
    }
}
